package com.lej.core.binding.viewadapter.view

import android.graphics.Rect
import android.view.TouchDelegate
import android.view.View
import android.view.ViewGroup
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.core.view.doOnLayout
import androidx.core.view.updateLayoutParams
import androidx.databinding.BindingAdapter
import com.lej.core.dsl.dp
import com.lej.core.utils.extention.dp2Px
import com.qmuiteam.qmui.kotlin.onClick


/**
 * requireAll 是意思是是否需要绑定全部参数, false为否
 * View的onClick事件绑定
 * onClickCommand 绑定的命令,
 * isThrottleFirst 是否开启防止过快点击
 */
@BindingAdapter(value = ["onClickSafe"])
fun View.onClickSafe(listener: View.OnClickListener?) {
    onClick {
        listener?.onClick(it)
    }
}

/*增加可点击区域**/
@BindingAdapter(
    value = ["touchPadding"]
)
fun View.touchPadding(touchPadding: Int) {
    this.doOnLayout {
        val bounds = Rect()
        val padding = touchPadding.dp2Px()
        getHitRect(bounds)
        bounds.top -= padding
        bounds.bottom += padding
        bounds.left -= padding
        bounds.right += padding
        (parent as View?)?.touchDelegate = TouchDelegate(bounds, this)
    }
}
@BindingAdapter(
    value = ["horizontal_bias"]
)
fun View.horizontalBias(bias: Float) {
    updateLayoutParams<ConstraintLayout.LayoutParams> {
        horizontalBias = bias
    }
}

@BindingAdapter("layout_height")
fun View.setLayoutHeight(height: Int) {
    updateLayoutParams<ViewGroup.LayoutParams> {
        this.height = height.dp
    }
}

@BindingAdapter("layout_height")
fun View.setLayoutHeightPx(height: Int) {
    updateLayoutParams<ViewGroup.LayoutParams> {
        this.height = height
    }
}

@BindingAdapter("layout_width")
fun View.setLayoutWidth(width: Int) {
    updateLayoutParams<ViewGroup.LayoutParams> {
        this.width = width.dp
    }
}

@BindingAdapter("layout_width")
fun View.setLayoutWidthPx(width: Int) {
    updateLayoutParams<ViewGroup.LayoutParams> {
        this.width = width
    }
}